from sqlalchemy import Column, Integer, String, DateTime, Table, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.orm.session import Session

from airflow.models.base import Base
from airflow.models.idata_auth_resource import AuthResource
from airflow.models.idata_auth_user_role import AuthUserRole
from airflow.utils import dates
from airflow.utils.session import provide_session


class AuthRole(Base):
    """the class to get user info."""

    __tablename__ = "idata_auth_role"
    __table_args__ = {"useexisting": True}

    id = Column(Integer, primary_key=True, autoincrement=True)
    role_name = Column(String(32))
    weight = Column(Integer)
    create_time = Column(DateTime)
    enable = Column(Integer)

    def __init__(self, role_name, weight, create_time):
        self.role_name = role_name
        self.weight = weight
        self.create_time = create_time
        self.enable = 0

    @staticmethod  # 静态方法
    @provide_session
    def get_role(rid, oa_user_name, session: Session = None):
        q = session.query(AuthRole).outerjoin(AuthUserRole, AuthUserRole.role_id == AuthRole.id)
        if rid:
            q = q.filter(AuthRole.id == rid)
        if oa_user_name:
            q = q.filter(AuthUserRole.oa_user_name == oa_user_name)
        return q.all()

    @staticmethod  # 静态方法
    @provide_session
    def get_roles(session: Session = None):
        return session.query(AuthRole).all()

    @staticmethod  # 静态方法
    @provide_session
    def get_roles_page(page, session: Session = None):
        return session.query(AuthRole).order_by(AuthRole.create_time).paginate(page, 10, error_out=False)

    @staticmethod  # 静态方法
    @provide_session
    def add_roles(role, session: Session = None):
        return session.add(role)

    @staticmethod  # 静态方法
    @provide_session
    def delete_role(id, session: Session = None):
        role = session.query(AuthRole).filter(AuthRole.id == id).first()
        if role is None:
            return
        else:
            return session.delete(role)

    @staticmethod  # 静态方法
    @provide_session
    def update_role(role, session: Session = None):
        result = session.query(AuthRole).filter(AuthRole.id == role.id).first()
        if result is None:
            return
        else:
            return session.merge(role)

    def to_json(self):
        if self is None:
            return None
        data = {
            'id': self.id,
            'role_name': self.role_name,
            'weight': self.weight,
            'create_time': dates.to_milliseconds(self.create_time),
            'resources': list(map(AuthResource.to_json, self.resources)),
            'enable': self.enable
        }
        return data
